<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/8/13
 * Time: 16:52
 */

namespace app\api\model;


use think\Db;
use think\Exception;
use traits\model\SoftDelete;

class Product extends BaseModel
{
    use SoftDelete;
    /**
     * 隐藏字段
     * @var array
     */
    protected  $hidden=['delete_time','create_time','update_time','pivot','from'];

    protected $autoWriteTimestamp = true;
    /**
     * 与category表一对一关系
     * @return \think\model\relation\BelongsTo
     */
    public function category(){
        return $this->belongsTo('Category','category_id','id');
    }
    /**
     * 与product_image一对多关联
     * @return \think\model\relation\HasMany
     */
    public function imgs(){
        return $this->hasMany('ProductImage','product_id','id');
    }
    /**
     * 与product_picture一对多关联
     * @return \think\model\relation\HasMany
     */
    public function pictures(){
        return $this->hasMany('ProductPicture','product_id','id');
    }
    /**
     * 与product_property一对多关联
     * @return \think\model\relation\HasMany
     */
    public function propertys(){
        return $this->hasMany('ProductProperty','product_id','id');
    }
    /**
     * 图片地址拼接
     * @param $value
     * @param $data
     * @return string
     */
    public function getMainImgUrlAttr($value,$data){
        return $this->prefixImg($value,$data);
    }
    /**
     * 获取最新商品
     * @param $count
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getMostRecent($count){
        $result = self::limit($count)->order('create_time desc')->select();
        return $result;
    }

    /**
     * 获取分类商品
     * @param $category
     * @param $count
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getProductAllInCategory($category,$t_id,$page,$count){
        $result = self::where('category_id','=',$category)
            ->where('grounding','=',1)
            ->where('t_id','=',$t_id)
            ->limit(($page-1)*$count,$count)
            ->order('create_time desc')
            ->select();
        return $result;
    }

    /**
     * 获取商品详情
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static  function getProductDetail($id){
        $result = self::with([
            'imgs'=>function($query){
                $query->with(['imgUrl'])->order('order','asc');
            }
        ])->with([
                'pictures'=>function($query){
                $query->with(['imgUrl'])->order('order','asc');
                }
            ])
            ->with(['propertys'])
            ->where('grounding','=',1)
            ->find($id);
        return $result;
    }
    /**
     * 获取订单表的所有商品信息
     * @param $list
     * @return false|static[]
     */
    public static function getProductAllInOrder($list){
        $result = Product::all($list)
                ->visible(['id','price','stock','name','main_img_url'])
                ->toArray();
        return $result;
    }
    /**
     * 支付成功后减少库存量
     * @param $productId
     * @param $count
     * @return int|true
     */
    public static function reduceOrderNum($productId,$count){
        $result =  self::where('id','=',$productId)
            ->setDec('stock',$count);
        return $result;
    }


/*------------------- cms 管理 -------------------*/
    /**
     * 根据条件查询商品
     * @param $where
     * @param $manager_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function  getProductList($where,$manager_id){
        $result =   self::with(['category'])
                    ->where('t_id','=',$manager_id)
                    ->where($where)
                    ->order('create_time desc')
                    ->select();
        foreach ($result as $value){
            $value->visible(['id','name','price','stock','main_img_url','property','summary','grounding','pay','t_id','category','create_time','update_time']);
            $value->category->visible(['name']);
        }
        return $result;
    }
    /**
     * 获取商品详情
     * @param $goods_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function  getProduct($goods_id){
        $result = self::with(['category'])
                ->with(['imgs'=>['imgUrl']])
                ->with(['pictures'=>['imgUrl']])
                ->where('id','=',$goods_id)
                ->find();
        foreach ($result->pictures as $value){
            $img = $value->visible(['img_url']);
            $img->img_url->visible(['id','url','key']);
        }
        foreach ($result->imgs as $value){
           $img =  $value->visible(['img_url']);
           if ($img->img_url != null){
               $img->img_url->visible(['id','url','key']);
           }
        }
        return $result;
    }
    /**
     * 创建商品
     * @param $info
     * @param $t_id
     * @return $this
     * @throws Exception
     */
    public static function createProduct($info,$t_id){
        $data['name'] = $info['name'];
        $data['price'] = $info['price'];
        $data['stock'] = $info['stock'];
        $data['category_id'] = $info['category_id'];
        $data['main_img_url'] = $info['main_img_url'];
        $data['property'] = $info['property'];
        $data['img_id'] = $info['img_id'];
        $data['grounding'] = $info['grounding'];
        $data['pay'] = $info['pay'];
        $data['t_id'] = $t_id;
        $data['from'] = $info['from'];
        Db::startTrans();
        try{
            $product = self::create($data);
            $product->imgs()->saveAll($info['img']);
            $product->pictures()->saveAll($info['picture']);
            Db::commit();
            return $product;
        }catch (Exception $exception){
            Db::rollback();
            throw $exception;
        }
    }
    /**
     * 更新商品
     * @param $info
     * @param $t_id
     * @return $this
     * @throws Exception
     */
    public static function updateProduct($info,$t_id){
        $data['id'] = $info['id'];
        $data['name'] = $info['name'];
        $data['price'] = $info['price'];
        $data['stock'] = $info['stock'];
        $data['category_id'] = $info['category_id'];
        $data['main_img_url'] = $info['main_img_url'];
        $data['property'] = $info['property'];
        $data['img_id'] = $info['img_id'];
        $data['grounding'] = $info['grounding'];
        $data['pay'] = $info['pay'];
        $data['t_id'] = $t_id;
        $data['from'] = $info['from'];
        $product = self::get($info['id']);
        Db::startTrans();
        try{
                $result = $product->save($data);
                $result2 = self::updateImg($info['img'], $data['id']);
                $result3 = self::updatePicture($info['picture'], $data['id']);
                Db::commit();
                if ($result || $result2 || $result3){
                    return true;
                }
                return false;
        }catch (Exception $exception){
            Db::rollback();
            throw $exception;
        }

    }
    /**
     *删除商品
     * @param $product_id
     * @return int
     */
    public static function deleteProduct($product_id){
        return self::destroy($product_id);
    }


    /**
     * 更新商品
     * @param $product
     * @param $category_id
     * @return $this
     */
    public static function removeProduct($product,$category_id){
        foreach ($product as $key=>$value){
            $array[] = $value['id'];
        }
        $data['category_id'] = $category_id;
        $result =  Product::where('id','in',$array)->update($data);
        return $result;
    }

    /**
     * 获取商品列表
     * @param $ids
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getProductListById($product){
        foreach ($product as $key=>$value){
            $array[] = $value['id'];
        }
        $result =  Product::where('id','in',$array)->select();
        return $result;
    }

    /**
     * 批量上下架
     * @param $product
     * @param $type
     * @return $this
     */
    public static function batchUPOrDown($product,$type){
        foreach ($product as $key=>$value){
            $array[] = $value['id'];
        }
        if ($type == 'up'){
            $data['grounding'] = 1;
        }elseif ($type =='down'){
            $data['grounding'] = 2;
        }
        $result = Product::where('id','in',$array)->update($data);
        return $result;
    }


    /**
     * 更新详情图片
     * @param $images
     * @param $product_id
     * @return array|false|int
     */
    private static function updateImg($images,$product_id){
        $array=[];
        $array2=[];
        $results = '';
        foreach ($images as $image){
            $array[] = $image['img_id'];
        }
        $imgs = ProductImage::getImgByProductId($product_id);

        foreach ($imgs as $img){
            $array2[] = $img['img_id'];
        }
        $result =  array_intersect($array,$array2);
        $add = array_diff($array,$result);
        $delete = array_diff($array2,$result);
        if (!empty($add)){
            foreach ($add as $key=>$value){
                $adds[$key]['img_id'] = $value;
                $adds[$key]['product_id'] = $product_id;
            }
          $results =(new ProductImage)->saveAll($adds);
        }
        if (!empty($delete)){
            $results = ProductImage::where("img_id",'in',$delete)
                        ->where('product_id','=',$product_id)
                        ->delete();
        }
        return $results;
    }

    /**
     * 更新商品主图
     * @param $images
     * @param $product_id
     * @return array|false|int
     */
    private static function updatePicture($images,$product_id){
        $array=[];
        $array2=[];
        $results = '';
        foreach ($images as $image){
            $array[] = $image['img_id'];
        }
        $imgs = ProductPicture::getImgByProductId($product_id);
        foreach ($imgs as $img){
            $array2[] = $img['img_id'];
        }
        $result =  array_intersect($array,$array2);
        $add = array_diff($array,$result);
        $delete = array_diff($array2,$result);
        if (!empty($add)){
            foreach ($add as $key=>$value){
                $adds[$key]['img_id'] = $value;
                $adds[$key]['product_id'] = $product_id;
            }
            $results = (new ProductPicture)->saveAll($adds);
        }
        if (!empty($delete)){
            $results = ProductPicture::where("img_id",'in',$delete)
                ->where('product_id','=',$product_id)
                ->delete();
        }
        return $results;
    }



}